package cn.wk.service.impl;

import cn.wk.client.AuthFeign;
import cn.wk.domain.LoginUser;
import cn.wk.domain.VipBase;
import cn.wk.domain.VipUser;
import cn.wk.dto.RegisterDto;
import cn.wk.exception.GlobalException;
import cn.wk.mapper.VipBaseMapper;
import cn.wk.mapper.VipUserMapper;
import cn.wk.service.IVipUserService;
import cn.wk.util.AjaxResult;
import cn.wk.util.StrUtils;
import cn.wk.util.encrypt.MD5;
import cn.wk.utils.ValidUtils;
import cn.wk.vo.SmsVo;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Random;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author wk
 * @since 2021-03-11
 */
@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipBaseMapper vipBaseMapper;
    @Autowired
    private AuthFeign authFeign;

    /**
     * 用户注册
     * @param registerDto
     */
    @Override
    @Transactional
    public void register(RegisterDto registerDto) {
        //效验数据
        //手机号
        String mobile = registerDto.getMobile();
        //密码
        String password = registerDto.getPassword();
        //创建通道
        Integer regChannel = registerDto.getRegChannel();
        //注册邀请码
        String invitationCode = registerDto.getInvitationCode();
        //手机验证码
        String smsCode = registerDto.getSmsCode();
        ValidUtils.assertNotNull(mobile,"手机号必填");
        ValidUtils.assertNotNull(password,"密码必填");
        ValidUtils.assertNotNull(regChannel,"参数错误，请刷新");
        ValidUtils.assertNotNull(smsCode,"短信验证码必填");
        VipUser vipUser = new VipUser();
        //检验手机号是否被注册
        vipUser.setPhone(mobile);
        VipUser dbUser = baseMapper.selectOne(vipUser);
        if(dbUser != null){
            throw new GlobalException("手机号已经被注册，请勿重复注册");
        }
        //效验手机验证码
        SmsVo redisCode = (SmsVo)redisTemplate.opsForValue().get("sms:" + mobile);
        ValidUtils.assertNotNull(redisCode,"验证码输入错误");
        ValidUtils.assertEq(smsCode,redisCode.getCode(),"验证码输入错误，请重新输入");
        //把数据保存到VipUser中
        vipUser.setCreateTime(new Date().getTime());
        //调用feign保存在auth login登录表中
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(registerDto.getMobile());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(registerDto.getPassword());
        loginUser.setPassword(encode);
        //门户网站用户 类型为1
        loginUser.setType(1);
        AjaxResult ajaxResult = authFeign.addOrUpdate(loginUser);
        ValidUtils.assertNotNull(ajaxResult,"loginuser保存失败");
        vipUser.setLoginId(Long.parseLong(ajaxResult.getResultObj().toString()));
        /*//密码要进行md5加密
        //准备随机数（盐值）
        String salt = StrUtils.getRandomString(10);
        String md5Password = MD5.getMD5(salt + password);
        vipUser.setSalt(salt);
        vipUser.setPassword(md5Password);*/
        //位状态保存  注册的时候位状态应该是0
        vipUser.addBitState(VipUser.BITSTATE_PHONE);
        //存入user数据库
        baseMapper.insert(vipUser);
        //准备vipbase
        VipBase vipBase = new VipBase();
        vipBase.setRegChannel(regChannel);
        vipBase.setSsoId(vipUser.getId());
        vipBase.setCreateTime(System.currentTimeMillis());
        vipBase.setRegTime(System.currentTimeMillis());
        //去查询注册邀请码
        VipBase vipBaseUser = new VipBase();
        if(invitationCode!=null && invitationCode.trim()!=""){
            vipBaseUser.setInvitationCode(invitationCode);
            VipBase one = vipBaseMapper.selectOne(vipBaseUser);
            //看其是否存在
            if(one == null){
                throw new GlobalException("错误的注册邀请码，可以不输入");
            }
            //保存邀请人id
            vipBase.setReferId(one.getSsoId());
        }
        //这里为新创建的用户生成一个注册码 这里为保持唯一性用两个随机数
        String randomString1 = StrUtils.getRandomString(3);
        String randomString2 = StrUtils.getComplexRandomString(3);
        vipBase.setInvitationCode(randomString1+randomString2);
        //存入base数据库
        vipBaseMapper.insert(vipBase);
    }
}
